# -*- coding: utf-8 -*-
import os
import time
import json
import threading
import rospy
import rsa_util
from std_msgs.msg import String

import paho.mqtt.client as mqtt


class AttributeReceiver(object):
    def __init__(self, node_name):
        self.client_id = "robot_north_866562"
        self.node_name = node_name
        self.host = "mq.richwin8.com" # mq.richwin8.com
        self.port = "1883"
        self.topic = "Robot.north"
        self.mqtt_sub = rospy.Subscriber("MQTTReceiver", String, self._on_receive, queue_size=20)
        self.heatbeat_sub = rospy.Subscriber("MQTTHeatbeat", String, self._on_receive, queue_size=20)
        self.barcode_sub = rospy.Subscriber("barcode", String, self._barcode_receive, queue_size=10)
        self.__client = mqtt.Client(protocol=mqtt.MQTTv311,client_id=self.client_id)
        self.__client.on_connect = self._on_connect
        self.__client.on_message = self._on_message
        rospy.on_shutdown(self.__client.disconnect)
        rospy.on_shutdown(self.__client.loop_stop)

    def connect(self):
        rospy.loginfo('Connect mqtt broker')
        self.__client.connect(self.host, port=self.port, keepalive=600)
        self.__client.loop_start()
        return self

    def start(self):
        rospy.loginfo('AttributeReceiver start : %s'%self.node_name)
        rospy.spin()
        rospy.loginfo('AttributeReceiver stop : %s'%self.node_name)
        # self.heartbeat()
        # threading.Thread(target=self.heartbeat)

    def _on_connect(self, client, userdata, flags, response_code):
        rospy.loginfo('mqtt_receiver connect status=%s'%response_code)      

    def _on_message(self, client, userdata, msg):
        payload = str(msg.payload)
        rospy.loginfo('mqtt_receiver command msg =%s'%payload)

    def _on_receive(self, data):
        rospy.loginfo('received message from ros : %s'% data.data)
        timestamp = int(round(time.time() * 1000))
        dev_id = "866562"
        seqkey = "junyivision"
        sign = rsa_util.md5_sign(dev_id+str(timestamp)+seqkey,seqkey)
        data_dict = eval(data.data)
        msg_dict = {"seqnum": dev_id, "timestamp": timestamp,
                    "sign": sign, "data": ""}
        rest_dict = dict(data_dict,**msg_dict)
        rest_json = json.dumps(rest_dict)
        rospy.loginfo('mqtt_receiver command data ='+str(rest_json))
        self.__client.publish(self.topic, rest_json)

    def _barcode_receive(self, data):
        rospy.loginfo('received message from ros : %s'% data.data)
        timestamp = int(round(time.time() * 1000))
        dev_id = "866562"
        seqkey = "junyivision"
        sign = rsa_util.md5_sign(dev_id+str(timestamp)+seqkey,seqkey)
        msg = data.data
        if isinstance(msg,str) and len(msg)>1:
            data_dict = {"method": "barcode.scan", "msg": msg}
            msg_dict = {"seqnum": dev_id, "timestamp": timestamp,
                    "sign": sign, "data": ""}
            rest_dict = dict(data_dict,**msg_dict)
            rest_json = json.dumps(rest_dict)
            rospy.loginfo('_barcode_receive data ='+str(rest_json))
            self.__client.publish(self.topic, rest_json)
